package com.dushan.boot.utils;

import org.springframework.context.ApplicationContext;

import java.util.Map;

/**
 * @Author：朗朗乾坤
 * @Package：com.dushan.boot.utils
 * @Project：DuShanHui
 * @name：SpringContextHolder
 * @Date：2024/1/24 13:55
 * @Filename：SpringContextHolder
 */
public class SpringContextHolder {

        /**
         * 保存ApplicationContext,可在项目中任意位置中取出ApplicationContext
         */
        private static ApplicationContext applicationContext;

        public static ApplicationContext getApplicationContext() {
            return applicationContext;
        }

        public static void setApplicationContext(ApplicationContext applicationContext) {
            SpringContextHolder.applicationContext = applicationContext;
        }

        /**
         * 通过name获取 Bean.
         * @param name
         * @return
         */
        public static Object getBean(String name){
            return applicationContext.getBean(name);
        }

        /**
         * 通过class获取class下的全部Bean.
         * @param clazz
         * @param <T>
         * @return
         */
        public static <T> Map<String, T> getBeans(Class<T> clazz){
            return applicationContext.getBeansOfType(clazz);
        }

        /**
         * 通过class获取Bean.
         * @param clazz
         * @param <T>
         * @return
         */
        public static <T> T getBean(Class<T> clazz){
            return applicationContext.getBean(clazz);
        }

}
